package cn.net.yugu.doraemon.dubbo.spi;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import com.alibaba.dubbo.common.Constants;

/**
 * @description:
 * @author: wanghongli
 * @create: 2022-07-12 13:30:21
 */
@Slf4j
@Activate(order = 100, group = {Constants.PROVIDER, Constants.CONSUMER})
public class DubboLogFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        final long mills = System.currentTimeMillis();
        final String name = invoker.getInterface().getName();
        final String methodNm = invocation.getMethodName();
        final Object[] args = invocation.getArguments();
        final boolean isProvider = RpcContext.getContext().isProviderSide();
        try {
            Result result = invoker.invoke(invocation);
            if (result.hasException()) {
                if (isProvider) {
                    log.warn("dubbo-provider:accept request exception, interface:{} method:{} params:{} exception:{}", name, methodNm, JSON.toJSONString(args), JSON.toJSONString(result));
                } else {
                    log.warn("dubbo-consumer:post request exception, interface:{} method:{} params:{} exception:{}", name, methodNm, JSON.toJSONString(args), JSON.toJSONString(result));
                }
            } else {
                if (isProvider) {
                    log.info("dubbo-provider:accept request success, interface:{} method:{} params:{} result:{} cost:{}", name, methodNm, JSON.toJSONString(args), JSON.toJSONString(result.getValue()), System.currentTimeMillis() - mills);
                } else {
                    log.info("dubbo-consumer:post request success, interface:{} method:{} params:{} result:{} cost:{}", name, methodNm, JSON.toJSONString(args), JSON.toJSONString(result.getValue()), System.currentTimeMillis() - mills);
                }
            }
            return result;
        } catch (Exception ex) {
            if (isProvider) {
                log.warn("dubbo-provider:accept request exception, interface:{} method:{} params:{} exception:{} cost:{}", name, methodNm, JSON.toJSONString(args), ex, System.currentTimeMillis() - mills);
            } else {
                log.warn("dubbo-consumer:post request exception, interface:{} method:{} params:{} exception:{} cost:{}", name, methodNm, JSON.toJSONString(args), ex, System.currentTimeMillis() - mills);
            }
            throw ex;
        }
    }
}
